CSS (Cascading Style Sheets) is a stylesheet language used for describing the look and formatting of HTML elements. It allows you to separate the presentation and layout aspects of a website from its content. To understand the basic syntax and selectors in CSS, let's break them down into their main components.
A CSS rule consists of two main parts: a selector and a declaration block. The selector targets specific HTML elements, while the declaration block contains one or more declarations that apply styling to the selected elements. Each declaration includes a CSS property and its value, separated by a colon. Multiple declarations within a block are separated by semicolons.
Here's the general structure of a CSS rule:
cssselector { property: value; property: value; }
For example, to style all paragraphs with a red font color and 16px font size, the CSS rule would look like this:
cssp {
color: red;
font-size: 16px;
}
Selectors are used to target specific HTML elements on a web page. There are various types of selectors in CSS:
a. Element (Type) Selector: Targets all elements of a specific type (e.g., p
, h1
, div
).
Example:
cssh1 {
font-size: 24px;
}
b. Class Selector: Targets elements with a specific class attribute. In CSS, class selectors are prefixed with a period (.
).
Example: HTML:
arduino<p class="highlight">Highlighted text</p>
CSS:
css.highlight {
background-color: yellow;
}
c. ID Selector: Targets an element with a specific ID attribute. In CSS, ID selectors are prefixed with a hash (#
). IDs should be unique within a page.
Example: HTML:
css<div id="header">Header content</div>
CSS:
css#header {
height: 100px;
background-color: blue;
}
d. Attribute Selector: Targets elements with a specific attribute or attribute value.
Example: HTML:
graphql<input type="text" placeholder="Username">
CSS:
cssinput[type="text"] {
border: 1px solid gray;
}
e. Pseudo-class Selector: Targets elements based on their state or position in the document. Pseudo-classes are prefixed with a colon (:
).
Example:
cssa:hover {
color: red;
}
p:first-child {
font-weight: bold;
}
f. Pseudo-element Selector: Targets specific parts of an element (e.g., the first letter or first line of a paragraph). Pseudo-elements are prefixed with two colons (::
).
Example:
cssp::first-letter {
font-size: 24px;
font-weight: bold;
}
g. Combinators: These allow you to target elements based on their relationships with other elements, such as descendant, child, adjacent sibling, or general sibling.
Example:
css/* Descendant combinator (space) */
nav li {
display: inline;
}
/* Child combinator (>) */
ul > li {
list-style-type: none;
}
/* Adjacent sibling combinator (+) */
h1 + p {
margin-top: 10px;
}
/* General sibling combinator (~) */
h1 ~ p {
font-size: 14px;
}
By understanding the basic syntax and different types of selectors in CSS, you can effectively target and style HTML elements to create visually appealing web designs.